﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLL;
using DAL_NhaSach;

namespace BLL_NhaSach
{
    public class HoaDonBLL : IProcessData
    {
        QLNhaSachEntities db;
        public HoaDonBLL(String cnStr)
        {
            db = new QLNhaSachEntities(cnStr);
        }
        public object getAllData()
        {
            return (from hs in db.HoaDons select new {hs.MaHD,hs.NhanVien.HoTen,hs.KhachHang.TenKH,hs.NgayBan });
        }

        public object findObjects(string find_content)
        {
            throw new NotImplementedException();
        }

        public object findObjects(int find_content)
        {
            return db.HoaDons.SingleOrDefault(p => p.MaHD == find_content);
        }

        public object sort(string Col_Name, bool state)
        {
            throw new NotImplementedException();
        }

        public bool addObject(object addObj)
        {
            HoaDon hd = (HoaDon)addObj;
            try
            {
                db.HoaDons.AddObject(hd);
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool deleteObject(int id)
        {
            HoaDon hd = db.HoaDons.SingleOrDefault(p => p.MaHD == id);
            if (hd != null)
            {
                db.HoaDons.DeleteObject(hd);
                try
                {
                    db.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            else return false;
        }

        public bool updateObject(object updateObj)
        {
            throw new NotImplementedException();
        }
        public int getNextID()
        {
            HoaDon hd = db.HoaDons.OrderByDescending(p => p.MaHD).FirstOrDefault();
            if (hd == null)
                return 1;
            else
            {
                int id = hd.MaHD + 1;
                return id;
            }
        }
        public bool updateSoLuong(String id,int soluong)
        {
            Sach kh = db.Saches.SingleOrDefault(p=>p.MaSach.Equals(id));
            if (kh != null)
            {
                try
                {
                    kh.SoLuongTon -= soluong;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            else return false;
        }
    }
}
